package com.suneast.suneaststore.modules.goodsdetail;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.common.CommonUtil;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.bean.goodsdetail.GoodsDetailBean;
import com.suneast.suneaststore.bean.goodsdetail.ItemShopCart2UpLoading;
import com.suneast.suneaststore.bean.goodsdetail.SpecsDataBean;
import com.suneast.suneaststore.modules.goodsdetail.event.AddGoodsToCartResult;
import com.suneast.suneaststore.modules.goodsdetail.event.BottomPageChangeEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.CollectGoodsResult;
import com.suneast.suneaststore.modules.goodsdetail.event.GetDetailEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.GotGoodsCollectState;
import com.suneast.suneaststore.modules.goodsdetail.event.GotSpecsDataEvent;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class GoodsHandler {
    static void requestDetail(int id) {
        RestClient.builder()
                .url(API.GOODS_DETAIL)
                .params("id", id)
                .success((String response) -> {
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        JSONObject goodsJObj = dataJObj.getJSONObject("goods");
                        GoodsDetailBean bean = new GoodsDetailBean();
                        if (goodsJObj != null) {
                            bean.setId(goodsJObj.getIntValue("id"));
                            bean.setType(goodsJObj.getIntValue("type"));
                            bean.setBrandId(goodsJObj.getIntValue("brand"));
                            bean.setPcate(goodsJObj.getIntValue("pcate"));
                            bean.setTitle(goodsJObj.getString("title"));
                            bean.setMerchId(goodsJObj.getIntValue("merchid"));
                            bean.setThumbList(JSON.parseArray(goodsJObj.getJSONArray("thumbs")
                                    .toJSONString(),String.class));
                            bean.setThumb(goodsJObj.getString("thumb"));
                            bean.setTotal(goodsJObj.getDouble("total"));
                            bean.setUnit(goodsJObj.getString("unit"));
                            bean.setSales(goodsJObj.getIntValue("sales"));
                            bean.setMemberPrice(goodsJObj.getString("memberprice"));
                            bean.setD2Price(goodsJObj.getString("D2_price"));
                            bean.setD2Discount(goodsJObj.getString("D2_discount"));
                            bean.setBrandName(goodsJObj.getString("brandname"));
                            bean.setFreight(goodsJObj.getIntValue("freight"));
                            bean.setExpressAddress(goodsJObj.getString("express_address"));
                            bean.setFavourable(goodsJObj.getString("favourable"));
                        }
                        JSONObject commentJObj = dataJObj.getJSONObject("comment");
                        bean.setTotalComment(commentJObj.getIntValue("total"));
                        bean.setGoodRate(commentJObj.getIntValue("goodrate"));
                        JSONObject commentObj = commentJObj.getJSONObject("info");
                        if (commentObj != null) {
                            bean.setNoComment(false);
                            bean.setLastCommentUserHeadImgUrl(commentObj.getString("headimgurl"));
                            bean.setLastCommentUserName(commentObj.getString("nickname"));
                            bean.setLastComment(commentObj.getString("content"));
                        } else {
                            bean.setNoComment(true);
                        }
                        EventBus.getDefault().post(new GetDetailEvent(bean));
                    }
                })
                .build()
                .post();
    }

    static void requestDetailInStore(int id, int merchId) {
        RestClient.builder()
                .url(API.GOODS_DETAIL)
                .params("id", id)
                .params("merchid", merchId)
                .success((String response) -> {

                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        JSONObject goodsJObj = dataJObj.getJSONObject("goods");
                        GoodsDetailBean bean = new GoodsDetailBean();
                        if (goodsJObj != null) {
                            bean.setId(goodsJObj.getIntValue("id"));
                            bean.setType(goodsJObj.getIntValue("type"));
                            bean.setBrandId(goodsJObj.getIntValue("brand"));
                            bean.setPcate(goodsJObj.getIntValue("pcate"));
                            bean.setTitle(goodsJObj.getString("title"));
                            bean.setMerchId(goodsJObj.getIntValue("merchid"));
                            ArrayList<String> thumbsArray = new ArrayList<>();
                            JSONArray thumbsJArray = goodsJObj.getJSONArray("thumbs");
                            if (thumbsJArray != null && thumbsJArray.size() > 0) {
                                for (int i = 0, length = thumbsJArray.size(); i < length; i++) {
                                    thumbsArray.add(thumbsJArray.getString(i));
                                }
                            }
                            bean.setThumbList(thumbsArray);
                            bean.setThumb(goodsJObj.getString("thumb"));
                            bean.setTotal(goodsJObj.getDouble("total"));
                            bean.setUnit(goodsJObj.getString("unit"));
                            bean.setSales(goodsJObj.getIntValue("sales"));
                            bean.setMemberPrice(goodsJObj.getString("memberprice"));
                            bean.setD2Price(goodsJObj.getString("D2_price"));
                            bean.setD2Discount(goodsJObj.getString("D2_discount"));
                            bean.setBrandName(goodsJObj.getString("brandname"));
                            bean.setFreight(goodsJObj.getIntValue("freight"));
                            bean.setExpressAddress(goodsJObj.getString("express_address"));
                            bean.setFavourable(goodsJObj.getString("favourable"));
                        }
                        JSONObject commentJObj = dataJObj.getJSONObject("comment");
                        bean.setTotalComment(commentJObj.getIntValue("total"));
                        bean.setGoodRate(commentJObj.getIntValue("goodrate"));
                        JSONObject commentObj = commentJObj.getJSONObject("info");
                        if (commentObj != null) {
                            bean.setNoComment(false);
                            bean.setLastCommentUserHeadImgUrl(commentObj.getString("headimgurl"));
                            bean.setLastCommentUserName(commentObj.getString("nickname"));
                            bean.setLastComment(commentObj.getString("content"));
                        } else {
                            bean.setNoComment(true);
                        }
                        EventBus.getDefault().post(new GetDetailEvent(bean));
                    }
                })
                .build()
                .post();
    }

    public static void requestSpecsData(int id) {
        RestClient.builder()
                .url(API.GOODS_SPEC)
                .params("id", id)
                .success((String response) -> {
                    LatteLogger.json("test", response);
                    JSONObject dataJObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataJObj != null) {
                        SpecsDataBean bean = JSON.parseObject(dataJObj.toJSONString(), SpecsDataBean.class);
                        EventBus.getDefault().post(new GotSpecsDataEvent(bean));
                    }
                })
                .error((code, msg) -> {
                    LatteLogger.e("error", "requestSpecsData error code = " + code + " msg = " + msg);
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestSpecsData failure ");
                })
                .build()
                .post();
    }

    static void addGoodsToCart(ItemShopCart2UpLoading itemShopCart) {
        RestClient.builder()
                .url(API.ADD_TO_CART)
                .params("token", AccountManager.getToken())
                .params("id", itemShopCart.getGoodsId())
                .params("merchid", itemShopCart.getMerchId())
                .params("total", itemShopCart.getCount())
                .params("optionId", itemShopCart.getOptionId())
                .params("width", itemShopCart.getWidth())
                .params("height", itemShopCart.getHeight())
                .params("is_machining", itemShopCart.isProcess() ? 1 : 0)
                .params("is_install", itemShopCart.isInstall() ? 1 : 0)
                .params("is_suit", itemShopCart.isSuit() ? 1 : 0)
                .params("is_custom", itemShopCart.isCustom() ? 1 : 0)
                .success((String response) -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new AddGoodsToCartResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new AddGoodsToCartResult(Flag.Result.FAILURE));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new AddGoodsToCartResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "addGoodsToCart failure");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new AddGoodsToCartResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "addGoodsToCart error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    public static void requestGoodsIntro(int id) {
        RestClient.builder()
                .url(API.GOODS_CONTENT)
                .params("id", id)
                .success(response ->
                        EventBus.getDefault().post(new BottomPageChangeEvent(0, response)))
                .build()
                .get();
    }

    public static void requestGoodsParamet(int id) {
        RestClient.builder()
                .url(API.GOODS_PARAMET)
                .success(response ->
                        EventBus.getDefault().post(new BottomPageChangeEvent(1, response)))
                .params("id", id)
                .build()
                .get();
    }

    public static void requestGoodsRecommand(int id) {
        RestClient.builder()
                .url(API.GOODS_RECOMMAND)
                .success((String response) -> {
                    EventBus.getDefault().post(new BottomPageChangeEvent(3, response));
                })
                .params("id", id)
                .build()
                .get();
    }

    static void collectGoodsOrNot(int id, int type) {
        RestClient.builder()
                .url(API.COLLECT_OR_UN_COLLECT_GOODS)
                .params("token", AccountManager.getToken())
                .params("goodsid", id)
                .success((String response) -> {
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        int resultType = dataJObj.getIntValue("type");
                        EventBus.getDefault().post(new CollectGoodsResult(Flag.Result.SUCCEED, resultType));
                    } else {
                        EventBus.getDefault().post(new CollectGoodsResult(Flag.Result.FAILURE, type));
                        LatteLogger.e("error", "collectGoodsOrNot failure ");
                    }
                })
                .error((code, msg) -> {
                    LatteLogger.e("error", "collectGoodsOrNot error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new CollectGoodsResult(Flag.Result.FAILURE, type));

                })
                .failure(() -> {
                    LatteLogger.e("error", "collectGoodsOrNot failure ");
                    EventBus.getDefault().post(new CollectGoodsResult(Flag.Result.FAILURE, type));
                })
                .build()
                .get();
    }

    public static void getGoodsCollectState(int id) {
        RestClient.builder()
                .url(API.GET_GOODS_COLLECT_STATE)
                .params("token", AccountManager.getToken())
                .params("goodsid", id)
                .success((String response) -> {
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        EventBus.getDefault().post(new GotGoodsCollectState(Flag.Result.SUCCEED,
                                dataJObj.getIntValue("status")));
                    } else {
                        EventBus.getDefault().post(new GotGoodsCollectState(Flag.Result.FAILURE, 0));
                        LatteLogger.e("error",
                                "getGoodsCollectState() response success,but code = "
                                        + rootJObj.getIntValue("code")
                                        + " msg = " + rootJObj.getString("msg"));
                    }
                })
                .error((code, msg) -> {
                    EventBus.getDefault().post(new GotGoodsCollectState(Flag.Result.FAILURE, 0));
                    LatteLogger.e("error", "getGoodsCollectState error code = "
                            + code + " msg = " + msg);
                })
                .failure(() -> {
                    EventBus.getDefault().post(new GotGoodsCollectState(Flag.Result.FAILURE, 0));
                    LatteLogger.e("error", "getGoodsCollectState failure ");

                })
                .build()
                .get();
    }
}
